package com.learning.cloud2020.controller;

import com.learning.cloud2020.Constance;
import com.learning.cloud2020.entities.Payment;
import com.learning.cloud2020.loadbalancer.Loadbalancer;
import com.learning.cloud2020.model.CommonResult;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/rest")
public class ConsumerController {

    //    private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://" + Constance.PAYMENT_SERVER_NAME;

    private final RestTemplate restTemplate;

    public ConsumerController(RestTemplate restTemplate, Loadbalancer loadbalancer, DiscoveryClient discoveryClient) {
        this.restTemplate = restTemplate;
        this.loadbalancer = loadbalancer;
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("/payment/{id}")
    public CommonResult<Payment> getById(@PathVariable Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, CommonResult.class);
    }

    @GetMapping("/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    private final Loadbalancer loadbalancer;
    private final DiscoveryClient discoveryClient;

    @GetMapping("/payment/mylb")
    public CommonResult getPaymentLB(Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances(Constance.PAYMENT_SERVER_NAME);
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }
        ServiceInstance instance = loadbalancer.instances(instances);
        URI uri = instance.getUri();
        //TODO 必须注释掉LoadBalance注解，否则会根据ip地址作为服务名去查找微服务
        return restTemplate.getForObject(uri + "/payment/" + id, CommonResult.class);

    }


}
